package com.tempjob.admin.controller;

import com.anwen.mongo.conditions.query.LambdaQueryChainWrapper;
import com.anwen.mongo.model.PageParam;
import com.anwen.mongo.model.PageResult;
import com.tempjob.admin.security.annotation.AdminLogAnnotation;
import com.tempjob.admin.security.annotation.AdminLogIgore;
import com.tempjob.admin.security.annotation.AdminPassportSSO;
import com.tempjob.common.businesss.mongo.entity.SysPermission;
import com.tempjob.common.businesss.mongo.entity.SysRole;
import com.tempjob.common.businesss.mongo.entity.SysRolePermission;
import com.tempjob.common.businesss.mongo.service.SysRoleService;
import com.tempjob.common.businesss.service.MongoBeanUtil;
import com.tempjob.common.businesss.service.UserPermissionService;
import com.tempjob.common.dto.admin.QueryRoleDTO;
import com.tempjob.common.exception.BusinessException;
import com.tempjob.common.utils.CachedBeanCopier;
import com.tempjob.common.vo.admin.PermissionRespNode;
import com.tempjob.common.vo.admin.RolePermissionOperationReqVO;
import com.tempjob.common.vo.admin.UserRoleOperationReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @version V1.0
 */
@RequestMapping("/sys/role")
@RestController
@Api(tags = "权限管理", value = "角色管理")
@AdminPassportSSO
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class RoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    private MongoBeanUtil mongoBeanUtil;

    @PostMapping("/del/{id}")
    @ApiOperation(value = "删除角色接口")
    @AdminLogAnnotation(title = "角色管理", action = "删除角色")
    public Object deleted(@PathVariable String id) {
        if (id.equals("65f00b3cdd537631cd36a01f")) {
            throw new BusinessException("删除失败");
        }
        userPermissionService.deletedRole(id);
        return true;
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新角色信息接口")
    @AdminLogAnnotation(title = "角色管理", action = "更新角色信息")
    public Object updateDept(@RequestBody SysRole vo) {
        if (vo.getId() == null) {
            userPermissionService.addRole(vo);
            return true;
        }
        if (vo.getId().equals(1L)) {
            throw new BusinessException("删除失败");
        }
        userPermissionService.updateRole(vo);
        return true;
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "查询角色详情接口")
    @AdminLogAnnotation(title = "角色管理", action = "查询角色详情")
    public Object detailInfo(@PathVariable("id") String id) {
        return userPermissionService.detailInfo(id);
    }

    @PostMapping("/list")
    @ApiOperation(value = "分页获取角色信息接口")
//    @LogAnnotation(title = "角色管理", action = "分页获取角色信息")
    @AdminLogIgore
    public Object pageInfo(@RequestBody(required = false) QueryRoleDTO vo) {
        if (vo == null) {
            vo = new QueryRoleDTO();
        }
        PageParam page = new PageParam(vo.getPage(), vo.getSize());
        LambdaQueryChainWrapper queryWrapper = sysRoleService.lambdaQuery();
        if (StringUtils.isNotBlank(vo.getOrder()) && StringUtils.isNotBlank(vo.getSort())) {
            if (vo.getSort().equalsIgnoreCase("asc")) {
                queryWrapper.orderByAsc(vo.getOrder());
            } else {
                queryWrapper.orderByDesc(vo.getOrder());
            }
        } else {
            queryWrapper.orderByDesc("id");
        }
        queryWrapper.ne("id", 1);
        queryWrapper.like(StringUtils.isNotBlank(vo.getName()), "name", vo.getName());
        queryWrapper.gt(StringUtils.isNotBlank(vo.getStartTime()), "create_time", vo.getStartTime());
        queryWrapper.lt(StringUtils.isNotBlank(vo.getEndTime()), "create_time", vo.getEndTime());
        queryWrapper.eq(vo.getStatus() != null, "status", vo.getStatus());
        PageResult<SysRole> pageInfo = sysRoleService.page(queryWrapper, page);
        if (!pageInfo.getContentData().isEmpty()) {
            List<String> roleIds = pageInfo.getContentData().stream().map(SysRole::getId).collect(Collectors.toList());
            List<SysRolePermission> rolePermission = mongoBeanUtil.getSysRolePermissionService().lambdaQuery().in(SysRolePermission::getRoleId, roleIds).list();
            Set<String> permissionIds = rolePermission.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toSet());
            List<SysPermission> permissions = permissionIds.isEmpty() ? new ArrayList<>() : mongoBeanUtil.getSysPermissionService().getByIds(permissionIds);
            for (SysRole contentDatum : pageInfo.getContentData()) {
                List<PermissionRespNode> permissionRespNodes = new ArrayList<>();
                List<String> rolePermissionIds = rolePermission.stream().filter(i -> i.getRoleId().equals(contentDatum.getId())).map(SysRolePermission::getPermissionId).collect(Collectors.toList());
                if (!rolePermissionIds.isEmpty()) {
                    List<SysPermission> permissionList = permissions.stream().filter(i -> rolePermissionIds.contains(i.getId())).collect(Collectors.toList());
                    CachedBeanCopier.copyList(permissionList, permissionRespNodes, PermissionRespNode.class);
                    contentDatum.setPermissionRespNodes(permissionRespNodes);
                }
                contentDatum.setPermissionIds(rolePermissionIds);
            }
        }
        return pageInfo;
    }

    @PostMapping("/permission")
    @ApiOperation(value = "修改或者新增角色菜单权限接口")
    @AdminLogAnnotation(title = "角色和菜单关联接口", action = "修改或者新增角色菜单权限")
    public Object operationRolePermission(@RequestBody @Valid RolePermissionOperationReqVO vo) {
        userPermissionService.addRolePermission(vo);
        return true;
    }


    @PostMapping("/user/role")
    @ApiOperation(value = "修改或者新增用户角色接口")
    @AdminLogAnnotation(title = "用户和角色关联接口", action = "修改或者新增用户角色")
    public Object operationUserRole(@RequestBody @Valid UserRoleOperationReqVO vo) {
        userPermissionService.addUserRoleInfo(vo);
        return true;
    }

}
